import rclpy
from rclpy.node import Node
from base_interfaces_demo.srv import FaceDetectors
from sensor_msgs.msg import Image
from ament_index_python.packages import get_package_share_directory #获取功能包share目录绝对路径
import cv2
from cv_bridge import CvBridge
import os
class FaceDetectClient(Node):
    def __init__(self):
        super(). __init__('face_detection_client_node')   
        self.client=self.create_client(FaceDetectors,'/face_detection')
        self.bridge=CvBridge()
        self.test1_image_path=os.path.join(get_package_share_directory("py02_service"),"resource/test1.jpg")
        self.image=cv2.imread(self.test1_image_path)
        self.get_logger().info("人脸检测客户端已经启动！！！")
    def send_request(self):
        while not self.client.wait_for_service(1.0):
            self.get_logger().info("正在连接服务端")
        request=FaceDetectors.Request() 
        request.image=self.bridge.cv2_to_imgmsg(self.image)   
        future=self.client.call_async(request)
        rclpy.spin_until_future_complete(self,future)
        response=future.result()
        self.get_logger().info(f"接收到响应，共检测到{response.number}张人脸,耗时{response.use_time}s")
        self.show_response(response)    
    def show_response(self,response):
        for i in range(response.number):
            top=response.top[i]
            bottom=response.bottom[i]
            left=response.left[i]
            right=response.right[i]
            cv2.rectangle(self.image,(left,top),(right,bottom),(255,0,0),4)
        cv2.imshow('Face Detection Result',self.image)    
        cv2.waitKey(0) #也是阻塞的。会导致spin无法正常运转
def main():
    rclpy.init()
    node=FaceDetectClient()
    node.send_request()
    rclpy.spin(node)
    rclpy.shutdown()



if __name__=='__main__':
    main()
